package com.person.base.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;

import com.person.base.model.BaseDept;
import com.person.base.model.BaseRole;
import com.person.base.model.BaseUser;
import com.person.base.service.BaseUserService;
import com.person.commons.exception.InfrastructureException;
import com.person.commons.security.DES;
import com.person.commons.utils.Constants;
import com.person.commons.utils.DAO;
import com.person.commons.utils.FlipPageInfo;
import com.person.commons.utils.Getch2spell;
import com.person.sys.model.SysFunc;
import com.person.sys.model.SysLog;
import com.person.title.model.TitleClass;
import com.person.title.model.TitleFunc;

public class BaseUserServiceImpl implements BaseUserService {
	private DAO dao;
	private static final char SUCCESS = '1';
	private static final char FAIL = '0';
	private static final char FAIL_1 = '2';
	private static final char FAIL_2 = '3';

	public DAO getDao() {
		return dao;
	}

	public void setDao(DAO dao) {
		this.dao = dao;
	}

	@Override
	public char login(BaseUser user, HttpServletRequest request) {
		// TODO Auto-generated method stub
		String passWord = user.getUserPwd();

		if (StringUtils.isNotBlank(passWord)) {
			passWord = DES.encrypt(passWord);
		}

		String hql = "from BaseUser where userLogin ='" + user.getUserLogin()
				+ "' and userPwd= '" + passWord + "'";

		String hql2 = "from BaseUser where userLogin ='" + user.getUserLogin()
				+ "'";
		List<BaseUser> list1 = dao.find(hql2);

		if (list1.size() == 0) {

			dao.createLog(new SysLog(user.getUserLogin(), getLoginIp(request),
					"2", user.getUserLogin() + "不是该系统的注册用户登陆失败!"));

			return FAIL;// 用户名错误返回0
		} else {
			List list = dao.find(hql);
			if (list.size() == 0) {

				if (list1.size() > 0) {
					user = (BaseUser) list1.get(0);
					dao.createLog(new SysLog(user.getUserId(),
							getLoginIp(request), "2", user.getUserName()
									+ "因为密码输入错误登陆失败!"));
				}
				return FAIL_1;// 密码错误返回2

			} else {
				user = (BaseUser) list.get(0);

				if (user.getUserFlag().equals("0")) {

					request.getSession().setAttribute(Constants.SESSION_USER,user);

					String funcIdGroup = getPermissions(user);
					String assetIdGroup =getPermissions1(user);

					if (StringUtils.isNotBlank(funcIdGroup)) {
						funcIdGroup = funcIdGroup.substring(0, funcIdGroup.length() - 1);
						if (funcIdGroup.indexOf(",") != -1) {
							String[] func = funcIdGroup.split(",");
							request.getSession().setAttribute(Constants.ROLE_CODE, func);
						} else {
							String[] func = new String[1];
							func[0] = funcIdGroup;
							request.getSession().setAttribute(Constants.ROLE_CODE, func);
						}
					}
					if (StringUtils.isNotBlank(assetIdGroup)) {
						assetIdGroup = assetIdGroup.substring(0, assetIdGroup.length() - 1);
						if (assetIdGroup.indexOf(",") != -1) {
							String[] asset = assetIdGroup.split(",");
							request.getSession().setAttribute(Constants.ASSET_CODE, asset);
						} else {
							String[] asset = new String[1];
							asset[0] = assetIdGroup;
							request.getSession().setAttribute(Constants.ASSET_CODE, asset);
						}
					}

					dao.createLog(new SysLog(user.getUserId(),
							getLoginIp(request), "1", user.getUserName()
									+ "登陆成功!"));
					return SUCCESS;// 登陆成功返回1
				} else {
					return FAIL_2;// 用户名或者密码错误返回3
				}
			}
		}
	}

	private String getPermissions(BaseUser user) {
		String funcIdGroup = "";
		String roleId = user.getRoleId();
		if (StringUtils.isNotBlank(roleId)) {
			BaseRole role = new BaseRole();
			role = (BaseRole) dao.find(BaseRole.class, roleId);

			funcIdGroup += role.getFuncIdGroup();
		}
		String roleIdOther = user.getRoleIdOther();
		if (StringUtils.isNotBlank(roleIdOther)) {
			roleIdOther = roleIdOther.substring(0, roleIdOther.length() - 1);
			if (roleIdOther.indexOf(",") != -1) {
				String roles[] = roleIdOther.split(",");
				for (int i = 0; i < roles.length; i++) {
					BaseRole role = new BaseRole();
					role = (BaseRole) dao.find(BaseRole.class, roles[i]);

					funcIdGroup += role.getFuncIdGroup();
				}
			} else {

				BaseRole role = new BaseRole();
				role = (BaseRole) dao.find(BaseRole.class, roleIdOther);

				funcIdGroup += role.getFuncIdGroup();
			}
		}
		return funcIdGroup;
	}
	private String getPermissions1(BaseUser user) {
		String funcIdGroup = "";
		String roleId = user.getRoleId();
		if (StringUtils.isNotBlank(roleId)) {
			BaseRole role = new BaseRole();
			role = (BaseRole) dao.find(BaseRole.class, roleId);
			
			funcIdGroup += role.getAssetIdGroup();
		}
		String roleIdOther = user.getRoleIdOther();
		if (StringUtils.isNotBlank(roleIdOther)) {
			roleIdOther = roleIdOther.substring(0, roleIdOther.length() - 1);
			if (roleIdOther.indexOf(",") != -1) {
				String roles[] = roleIdOther.split(",");
				for (int i = 0; i < roles.length; i++) {
					BaseRole role = new BaseRole();
					role = (BaseRole) dao.find(BaseRole.class, roles[i]);
					
					funcIdGroup += role.getAssetIdGroup();
				}
			} else {
				
				BaseRole role = new BaseRole();
				role = (BaseRole) dao.find(BaseRole.class, roleIdOther);
				
				funcIdGroup += role.getAssetIdGroup();
			}
		}
		return funcIdGroup;
	}

	/**
	 * 获得IP地址
	 * 
	 * @return
	 */
	private String getLoginIp(HttpServletRequest request) {

		String ip = request.getHeader("X-Forwarded-For");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_CLIENT_IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}

		return ip;
	}

	@Override
	public char updatePassWord(String userPwd, String userPwd1,
			String userPwd2, String userId, HttpServletRequest request)
			throws InfrastructureException {
		// TODO Auto-generated method stub
		char s = '0';

		if (StringUtils.isNotBlank(userPwd)) {
			String hql = "from BaseUser where userId = '" + userId
					+ "' and userPwd ='" + DES.encrypt(userPwd) + "'";

			List list = dao.find(hql);
			if (!userPwd1.equals(userPwd2)) {
				s = FAIL_1;// 两次输入新密码不一致返回2
			} else {
				if (list.size() == 1) {
					BaseUser user = (BaseUser) list.get(0);
					if (StringUtils.isNotBlank(userPwd1)) {
						user.setUserPwd(DES.encrypt(userPwd1));
					} else {
						user.setUserPwd("");
					}
					dao.update(user);
					s = SUCCESS;// 密码修改成功返回1
				} else {
					s = FAIL_2;// 旧密码输入错误返回3
				}
			}
		} else {

			String hql = "from BaseUser where userId = '" + userId
					+ "' and userPwd =''";

			List list = dao.find(hql);
			if (!userPwd1.equals(userPwd2)) {
				s = FAIL_1;// 两次输入新密码不一致返回2
			} else {

				if (list.size() == 1) {
					BaseUser user = (BaseUser) list.get(0);
					if (StringUtils.isNotBlank(userPwd1)) {
						user.setUserPwd(DES.encrypt(userPwd1));
					} else {
						user.setUserPwd("");
					}
					dao.update(user);
					s = SUCCESS;// 密码修改成功返回1
				} else {
					s = FAIL_2;// 旧密码输入错误返回3
				}

			}
		}
		return s;
	}

	@Override
	public char create(BaseUser user, HttpServletRequest request) {
		// TODO Auto-generated method stub
		if (isUnique(user) == true) {
			String userName = user.getUserName();
			String userSpell = Getch2spell.getfirststr(userName);
			user.setUserSpell(userSpell);

			if (StringUtils.isNotBlank(user.getUserPwd())) {
				user.setUserPwd(DES.encrypt(user.getUserPwd()));
			}

			String userId = (String) dao.save(user);

			// dao.createLog(new SysLog(user.getUserId(),
			// getLoginIp(request), "1", user.getUserName()
			// + "添加用户"+userName+"!"));
			return SUCCESS;
		} else {
			return FAIL;
		}
	}

	/**
	 * 判断登陆帐号是否唯一
	 * 
	 * @param user
	 * @return
	 */
	private boolean isUnique(BaseUser user) {
		boolean s = false;
		String hql = "";
		if (!StringUtils.isNotBlank(user.getUserId())) {

			hql = "from BaseUser where userLogin = '" + user.getUserLogin()
					+ "' ";
		} else {

			hql = "from BaseUser where userLogin = '" + user.getUserLogin()
					+ "' and userId != '" + user.getUserId() + "'";
		}

		List list = dao.find(hql);

		if (list.size() == 0) {
			s = true;
		}

		return s;
	}

	@Override
	public BaseUser findUserById(String userId) {
		// TODO Auto-generated method stub
		return (BaseUser) dao.find(BaseUser.class, userId);
	}

	@Override
	public List<BaseUser> searchEffectByDept(String departId) {

		String hql = "from BaseUser where deptId = '" + departId
				+ "' and userFlag = 0 order by userOrder";

		return dao.find(hql);
	}

	@Override
	public List<BaseUser> searchEffectByRole(String roleId) {

		String hql = "from BaseUser where roleId = '" + roleId
				+ "' and userFlag = 0 order by userOrder";

		return dao.find(hql);
	}

	@Override
	public FlipPageInfo searchEffectByDept(String departId, FlipPageInfo fpi) {
		// TODO Auto-generated method stub
		String hql = "select user,depart.deptName,role.roleName "
				+ " from BaseUser user,BaseDept depart,BaseRole role where "
				+ " user.deptId = depart.deptId and user.roleId = role.roleId and user.deptId = '"
				+ departId + "' and user.userFlag = 0 order by user.userOrder";
		FlipPageInfo pageDate = dao.findWithPaging(hql, fpi);

		if (pageDate != null) {

			return pageDate;
		} else {

			return new FlipPageInfo();
		}
	}

	@Override
	public FlipPageInfo searchEffectByUser(BaseUser user, FlipPageInfo fpi) {
		// TODO Auto-generated method stub
		String hql = "select user,depart.deptName,role.roleName "
				+ " from BaseUser user,BaseDept depart,BaseRole role where "
				+ " user.deptId = depart.deptId and user.roleId = role.roleId and user.userFlag = 0";

		if (StringUtils.isNotBlank(user.getUserLogin())) {
			hql += " and user.userLogin = '" + user.getUserLogin() + "'";
		} else if (StringUtils.isNotBlank(user.getUserName())) {
			hql += " and user.userName = '" + user.getUserName() + "'";
		} else if (StringUtils.isNotBlank(user.getUserAlias())) {
			hql += " and user.userAlias = '" + user.getUserAlias() + "'";
		} else if (StringUtils.isNotBlank(user.getUserSex())) {
			hql += " and user.userSex = '" + user.getUserSex() + "'";
		} else if (StringUtils.isNotBlank(user.getRoleId())) {
			hql += " and user.roleId = '" + user.getRoleId() + "'";
		} else if (StringUtils.isNotBlank(user.getDeptId())) {
			hql += " and user.deptId = '" + user.getDeptId() + "'";
		}

		hql += " order by user.userOrder";

		FlipPageInfo pageDate = dao.findWithPaging(hql, fpi);

		if (pageDate != null) {

			return pageDate;
		} else {

			return new FlipPageInfo();
		}
	}

	@Override
	public List<BaseUser> searchInEffectByDept(String departId) {
		// TODO Auto-generated method stub
		String hql = "from BaseUser where deptId = '" + departId
				+ "' and userFlag = 1";

		return dao.find(hql);
	}

	@Override
	public List<BaseUser> searchAllInAudit() {
		// TODO Auto-generated method stub
		String hql = "from BaseUser where userFlag = 2";

		return dao.find(hql);
	}

	@Override
	public List<BaseUser> searchAllInEffectByDept() {
		// TODO Auto-generated method stub

		String hql = "from BaseUser where userFlag = 1 order by userOrder";

		return dao.find(hql);
	}

	@Override
	public List<BaseUser> searchAllEffectByDept() {
		// TODO Auto-generated method stub

		String hql = "from BaseUser where userFlag = 0 order by userOrder";

		return dao.find(hql);
	}

	@Override
	public String userDepartTree(String departId, HttpServletRequest request) {
		// TODO Auto-generated method stub
		List<BaseDept> list = dao.find("from BaseDept where deptParent = '"
				+ departId + "' order by deptOrder");
		if (list != null && list.size() > 0) {
			// CTX
			String ctx = request.getContextPath();
			StringBuffer responseXML = new StringBuffer(
					"<?xml version='1.0' encoding='UTF-8'?><tree>");
			// 循环一级节点
			for (BaseDept department : list) {
				responseXML.append("<tree");
				// 节点名称
				responseXML.append(" text='" + department.getDeptName() + "'");
				// 节点超链接
				responseXML
						.append(" src='"
								+ ctx
								+ "/user/user_userInDepartTree.action?department.deptParent="
								+ department.getDeptId() + "'");
				// 节点超链接
				responseXML.append(" action='" + ctx
						+ "/user/user_managerUser.action?user.deptId="
						+ department.getDeptId() + "'");
				// 节点超链接目标
				responseXML.append(" target='mright'");
				// 节点图片
				responseXML
						.append(" icon='" + ctx + "/images/main/depart.gif'");
				// 节点打开图片
				responseXML.append(" openIcon='" + ctx
						+ "/images/main/depart.gif'");
				// 节点
				responseXML.append("/>");
			}
			responseXML.append("</tree>");

			return responseXML.toString();
		} else {
			return "<?xml version='1.0' encoding='UTF-8'?><tree></tree>";
		}
	}

	@Override
	public String userInDepartTree(String departId, HttpServletRequest request) {
		// TODO Auto-generated method stub
		String hql = "from BaseUser where deptId = '" + departId
				+ "' and userFlag = 0 order by userOrder";
		String hql1 = "from BaseDept where deptParent = '" + departId
				+ "' order by deptOrder";
		List<BaseUser> list = dao.find(hql);
		List<BaseDept> list1 = dao.find(hql1);
		if ((list != null && list.size() > 0)
				|| (list1 != null && list1.size() > 0)) {
			// CTX
			String ctx = request.getContextPath();
			StringBuffer responseXML = new StringBuffer(
					"<?xml version='1.0' encoding='UTF-8'?><tree>");

			if (list != null && list.size() > 0) {

				for (BaseUser user : list) {
					responseXML.append("<tree");
					// 节点名称
					responseXML.append(" text='" + user.getUserName() + "'");
					// 节点超链接
					responseXML.append(" action='" + ctx
							+ "/user/user_preModifyUser.action?user.userId="
							+ user.getUserId() + "'");
					// 节点超链接目标
					responseXML.append(" target='mright'");
					// 节点图片
					responseXML.append(" icon='" + ctx
							+ "/images/main/m_41.gif'");
					// 节点打开图片
					responseXML.append(" openIcon='" + ctx
							+ "/images/main/m_41.gif'");
					// 节点
					responseXML.append("/>");
				}

			}

			if (list1 != null && list1.size() > 0) {

				for (BaseDept depart : list1) {
					responseXML.append("<tree");
					// 节点名称
					responseXML.append(" text='" + depart.getDeptName() + "'");
					// 节点超链接
					responseXML
							.append(" src='"
									+ ctx
									+ "/user/user_userInDepartTree.action?department.deptParent="
									+ depart.getDeptId() + "'");
					// 节点超链接
					responseXML.append(" action='" + ctx
							+ "/user/user_managerUser.action?user.deptId="
							+ depart.getDeptId() + "'");
					// 节点超链接目标
					responseXML.append(" target='mright'");
					// 节点图片
					responseXML.append(" icon='" + ctx
							+ "/images/main/depart.gif'");
					// 节点打开图片
					responseXML.append(" openIcon='" + ctx
							+ "/images/main/depart.gif'");
					// 节点
					responseXML.append("/>");
				}

			}

			responseXML.append("</tree>");

			return responseXML.toString();

		} else {
			return "<?xml version='1.0' encoding='UTF-8'?><tree></tree>";
		}
	}

	@Override
	public String userInRoleTree(String roleId, HttpServletRequest request) {
		// TODO Auto-generated method stub
		String hql = "select user from BaseUser user where not exists(from Trainer trainer where trainer.userId=user.userId) and user.userFlag = 0 and ( user.roleId = '"
				+ roleId + "' or user.roleIdOther like '%" + roleId + "%') ";
		List<BaseUser> users = dao.find(hql);
		if (users != null && users.size() > 0) {
			// CTX
			String ctx = request.getContextPath();
			StringBuffer responseXML = new StringBuffer(
					"<?xml version='1.0' encoding='UTF-8'?><tree>");
			// 循环一级节点
			for (BaseUser user : users) {
				responseXML.append("<tree");
				// 节点名称
				responseXML.append(" text='" + user.getUserName() + "'");
				// 节点超链接
				responseXML
						.append(" action='"
								+ ctx
								+ "/trainer/trainer!preCreateTrainer.action?trainer.userId="
								+ user.getUserId() + "'");
				// 节点超链接目标
				responseXML.append(" target='mright'");
				// 节点图片
				responseXML
						.append(" icon='" + ctx + "/images/main/m_41.gif'");
				// 节点打开图片
				responseXML.append(" openIcon='" + ctx
						+ "/images/main/m_41.gif'");
				// 节点
				responseXML.append("/>");
			}
			responseXML.append("</tree>");

			return responseXML.toString();
		} else {
			return "<?xml version='1.0' encoding='UTF-8'?><tree></tree>";
		}
	}

	@Override
	public BaseUser innitByCode(String userCode) {
		// TODO Auto-generated method stub
		BaseUser user = new BaseUser();

		Pattern pattern = Pattern.compile("^\\d{15}(\\d{2}[A-Za-z0-9])?$");

		Matcher matcher = pattern.matcher(userCode);

		boolean result = matcher.matches();

		if (result == true) {
			if (userCode.length() == 18) {
				// 420113198404170025
				int year = Integer.parseInt(userCode.substring(6, 10));
				int month = Integer.parseInt(userCode.substring(10, 12));
				int date = Integer.parseInt(userCode.substring(12, 14));

				Calendar calendar = Calendar.getInstance();
				calendar.set(Calendar.YEAR, year);
				calendar.set(Calendar.MONTH, month - 1);
				calendar.set(Calendar.DAY_OF_MONTH, date);

				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

				try {
					user.setUserBirthday(sdf.parse(sdf.format(calendar
							.getTime())));
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				int sex = Integer.parseInt(userCode.substring(16, 17));

				System.out.println(userCode.substring(16, 17));
				if (sex % 2 == 1) {
					user.setUserSex("0");//
				} else {
					user.setUserSex("1");
				}

			} else if (userCode.length() == 15) {

				int year = Integer.parseInt("19" + userCode.substring(6, 7));
				int month = Integer.parseInt(userCode.substring(8, 9));
				int date = Integer.parseInt(userCode.substring(10, 11));

				Calendar calendar = Calendar.getInstance();
				calendar.set(Calendar.YEAR, year);
				calendar.set(Calendar.MONTH, month - 1);
				calendar.set(Calendar.DAY_OF_MONTH, date);

				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

				try {
					user.setUserBirthday(sdf.parse(sdf.format(calendar
							.getTime())));
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				int sex = Integer.parseInt(userCode.substring(12, 14));

				if (sex % 2 == 1) {
					user.setUserSex("0");
				} else {
					user.setUserSex("1");
				}
			}

		}
		return user;
	}

	@Override
	public char modify(BaseUser user, HttpServletRequest request) {
		// TODO Auto-generated method stub

		if (isUnique(user) == true) {
			String userName = user.getUserName();
			String userSpell = Getch2spell.getfirststr(userName);
			user.setUserSpell(userSpell);
			// user.setUserPwd(DES.encrypt(user.getUserPwd()));

			// dao.createLog(new SysLog(user.getUserId(),
			// getLoginIp(request), "1", user.getUserName()
			// + "修改用户"+userName+"!"));
			dao.update(user);
			return SUCCESS;
		} else {
			return FAIL;
		}
	}

	@Override
	public BaseUser searchUserById(String userId) {
		// TODO Auto-generated method stub
		BaseUser baseUser = new BaseUser();
		BaseUser user = new BaseUser();
		if (StringUtils.isNotBlank(userId)) {

			user = (BaseUser) dao.find(BaseUser.class, userId);
		}

		String hql = "";
		if (StringUtils.isNotBlank(user.getRoleId())
				&& StringUtils.isNotBlank(user.getDeptId())) {

			hql = "select user,depart.deptName,role.roleName "
					+ " from BaseUser user,BaseDept depart,BaseRole role where "
					+ " user.deptId = depart.deptId and user.roleId = role.roleId and user.userId = '"
					+ userId + "' ";

			Object[] obj = new Object[3];
			List list = dao.find(hql);
			if (list.size() == 1) {
				obj = (Object[]) list.get(0);

				baseUser = (BaseUser) obj[0];

				baseUser.setDeptName((String) obj[1]);

				baseUser.setRoleName((String) obj[2]);

				String roleIdOther = baseUser.getRoleIdOther();

				if (StringUtils.isNotBlank(roleIdOther)) {
					roleIdOther = roleIdOther.substring(0, roleIdOther
							.lastIndexOf(","));
					String roleNameOther = "";

					if (roleIdOther.indexOf(",") != -1) {
						String[] roleIds = roleIdOther.split(",");
						for (int i = 0; i < roleIds.length; i++) {
							BaseRole role = (BaseRole) dao.find(BaseRole.class,
									roleIds[i]);
							roleNameOther += role.getRoleName() + ",";
						}
					} else {
						BaseRole role = (BaseRole) dao.find(BaseRole.class,
								roleIdOther);
						roleNameOther = role.getRoleName() + ",";
					}

					baseUser.setRoleNameOther(roleNameOther);
				}

				String deptIdOther = baseUser.getDeptIdOther();

				if (StringUtils.isNotBlank(deptIdOther)) {
					deptIdOther = deptIdOther.substring(0, deptIdOther
							.lastIndexOf(","));
					String depatNameOther = "";

					if (deptIdOther.indexOf(",") != -1) {
						String[] deptIds = deptIdOther.split(",");
						for (int i = 0; i < deptIds.length; i++) {
							BaseDept dept = (BaseDept) dao.find(BaseDept.class,
									deptIds[i]);
							depatNameOther += dept.getDeptName() + ",";
						}
					} else {
						BaseDept dept = (BaseDept) dao.find(BaseDept.class,
								deptIdOther);
						depatNameOther = dept.getDeptName() + ",";
					}

					baseUser.setDeptNameOther(depatNameOther);
				}
			}
		} else if (StringUtils.isNotBlank(user.getRoleId())
				&& !StringUtils.isNotBlank(user.getDeptId())) {

			hql = "select user,role.roleName "
					+ " from BaseUser user,BaseRole role where "
					+ "  user.roleId = role.roleId and user.userId = '"
					+ userId + "' ";

			Object[] obj = new Object[2];
			List list = dao.find(hql);
			if (list.size() == 1) {
				obj = (Object[]) list.get(0);

				baseUser = (BaseUser) obj[0];

				baseUser.setRoleName((String) obj[1]);

				String roleIdOther = baseUser.getRoleIdOther();

				if (StringUtils.isNotBlank(roleIdOther)) {
					roleIdOther = roleIdOther.substring(0, roleIdOther
							.lastIndexOf(","));
					String roleNameOther = "";

					if (roleIdOther.indexOf(",") != -1) {
						String[] roleIds = roleIdOther.split(",");
						for (int i = 0; i < roleIds.length; i++) {
							BaseRole role = (BaseRole) dao.find(BaseRole.class,
									roleIds[i]);
							roleNameOther += role.getRoleName() + ",";
						}
					} else {
						BaseRole role = (BaseRole) dao.find(BaseRole.class,
								roleIdOther);
						roleNameOther = role.getRoleName() + ",";
					}

					baseUser.setRoleNameOther(roleNameOther);
				}

				String deptIdOther = baseUser.getDeptIdOther();

				if (StringUtils.isNotBlank(deptIdOther)) {
					deptIdOther = deptIdOther.substring(0, deptIdOther
							.lastIndexOf(","));
					String depatNameOther = "";

					if (deptIdOther.indexOf(",") != -1) {
						String[] deptIds = deptIdOther.split(",");
						for (int i = 0; i < deptIds.length; i++) {
							BaseDept dept = (BaseDept) dao.find(BaseDept.class,
									deptIds[i]);
							depatNameOther += dept.getDeptName() + ",";
						}
					} else {
						BaseDept dept = (BaseDept) dao.find(BaseDept.class,
								deptIdOther);
						depatNameOther = dept.getDeptName() + ",";
					}

					baseUser.setDeptNameOther(depatNameOther);
				}
			}
		} else if (!StringUtils.isNotBlank(user.getRoleId())
				&& StringUtils.isNotBlank(user.getDeptId())) {

			hql = "select user,depart.deptName "
					+ " from BaseUser user,BaseDept depart where "
					+ " user.deptId = depart.deptId and user.userId = '"
					+ userId + "' ";

			Object[] obj = new Object[2];
			List list = dao.find(hql);
			if (list.size() == 1) {
				obj = (Object[]) list.get(0);

				baseUser = (BaseUser) obj[0];

				baseUser.setDeptName((String) obj[1]);

				String roleIdOther = baseUser.getRoleIdOther();

				if (StringUtils.isNotBlank(roleIdOther)) {
					roleIdOther = roleIdOther.substring(0, roleIdOther
							.lastIndexOf(","));
					String roleNameOther = "";

					if (roleIdOther.indexOf(",") != -1) {
						String[] roleIds = roleIdOther.split(",");
						for (int i = 0; i < roleIds.length; i++) {
							BaseRole role = (BaseRole) dao.find(BaseRole.class,
									roleIds[i]);
							roleNameOther += role.getRoleName() + ",";
						}
					} else {
						BaseRole role = (BaseRole) dao.find(BaseRole.class,
								roleIdOther);
						roleNameOther = role.getRoleName() + ",";
					}

					baseUser.setRoleNameOther(roleNameOther);
				}

				String deptIdOther = baseUser.getDeptIdOther();

				if (StringUtils.isNotBlank(deptIdOther)) {
					deptIdOther = deptIdOther.substring(0, deptIdOther
							.lastIndexOf(","));
					String depatNameOther = "";

					if (deptIdOther.indexOf(",") != -1) {
						String[] deptIds = deptIdOther.split(",");
						for (int i = 0; i < deptIds.length; i++) {
							BaseDept dept = (BaseDept) dao.find(BaseDept.class,
									deptIds[i]);
							depatNameOther += dept.getDeptName() + ",";
						}
					} else {
						BaseDept dept = (BaseDept) dao.find(BaseDept.class,
								deptIdOther);
						depatNameOther = dept.getDeptName() + ",";
					}

					baseUser.setDeptNameOther(depatNameOther);
				}
			}
		} else {

			hql = "select user from BaseUser user where  user.userId = '"
					+ userId + "' ";

			List list = dao.find(hql);
			if (list.size() == 1) {
				baseUser = (BaseUser) list.get(0);

				String roleIdOther = baseUser.getRoleIdOther();

				if (StringUtils.isNotBlank(roleIdOther)) {
					roleIdOther = roleIdOther.substring(0, roleIdOther
							.lastIndexOf(","));
					String roleNameOther = "";

					if (roleIdOther.indexOf(",") != -1) {
						String[] roleIds = roleIdOther.split(",");
						for (int i = 0; i < roleIds.length; i++) {
							BaseRole role = (BaseRole) dao.find(BaseRole.class,
									roleIds[i]);
							roleNameOther += role.getRoleName() + ",";
						}
					} else {
						BaseRole role = (BaseRole) dao.find(BaseRole.class,
								roleIdOther);
						roleNameOther = role.getRoleName() + ",";
					}

					baseUser.setRoleNameOther(roleNameOther);
				}

				String deptIdOther = baseUser.getDeptIdOther();

				if (StringUtils.isNotBlank(deptIdOther)) {
					deptIdOther = deptIdOther.substring(0, deptIdOther
							.lastIndexOf(","));
					String depatNameOther = "";

					if (deptIdOther.indexOf(",") != -1) {
						String[] deptIds = deptIdOther.split(",");
						for (int i = 0; i < deptIds.length; i++) {
							BaseDept dept = (BaseDept) dao.find(BaseDept.class,
									deptIds[i]);
							depatNameOther += dept.getDeptName() + ",";
						}
					} else {
						BaseDept dept = (BaseDept) dao.find(BaseDept.class,
								deptIdOther);
						depatNameOther = dept.getDeptName() + ",";
					}

					baseUser.setDeptNameOther(depatNameOther);
				}
			}
		}

		return baseUser;
	}

	@Override
	public List<BaseUser> getAllBySpelllist(String spell) {
		// TODO Auto-generated method stub
		String hql = "from BaseUser where userSpell like '" + spell
				+ "%' and userFlag = 0 order by userOrder";

		List<BaseUser> users = dao.find(hql);
		return users;
	}

	@Override
	public List<BaseUser> getAllNoDept() {
		// TODO Auto-generated method stub
		String hql = "from BaseUser where userFlag = 0 and deptId = '' or deptId is null";

		List<BaseUser> users = dao.find(hql);
		return users;
	}

	@Override
	public char deleteUser(BaseUser user, HttpServletRequest request) {
		// TODO Auto-generated method stub

		dao.delete(user);

		// dao.createLog(new SysLog(user.getUserId(),
		// getLoginIp(request), "1", user.getUserName()
		// + "删除用户"+user.getUserName()+"!"));
		return SUCCESS;
	}

	@Override
	public void createLog(BaseUser admin, String ip, String message, String code) {
		// TODO Auto-generated method stub
		dao.createLog(new SysLog(admin.getUserId(), ip, code, message));
	}

	@Override
	public List<BaseUser> searchEffectByRoleTrainer(String roleId) {
		// TODO Auto-generated method stub
		String hql = "select user from BaseUser user where not exists(from Trainer trainer where trainer.userId=user.userId) and user.userFlag = 0 and ( user.roleId = '"
				+ roleId + "' or user.roleIdOther like '%" + roleId + "%') ";
		List<BaseUser> users = dao.find(hql);
		return users;
	}

	@Override
	public List<BaseRole> userInRoles() {
		// TODO Auto-generated method stub
		String hql = "from BaseRole where 1=1 order by roleOrder";
		List<BaseRole> roles = dao.find(hql);
		for (BaseRole baseRole : roles) {
			List<BaseUser> users = searchEffectByRoleTrainer(baseRole
					.getRoleId());
			baseRole.setUsers(users);
		}
		return roles;
	}

	/**
	 * 根据菜单链接，查找跟菜单相关联的栏目树形结构
	 * @param funcstr
	 * @return
	 */
	public List showFun(String funcstr){
		List templist=new ArrayList();
		List olist=new ArrayList();
		if(funcstr!=null&&!"".equals(funcstr)&&funcstr.length()!=32){
		templist=dao.find("from SysFunc where funcCode like '"+funcstr+"%'");
		if(null!=templist&&templist.size()>0){
			SysFunc func=(SysFunc)templist.get(0);
			String str=func.getMenuCodeGroup().substring(0, 2);
			
				olist=dao.find("select func,cla from TitleFunc func,TitleClass cla where cla.classCode='"+str+"' and " +
						"func.classCodeGroup like '"+str+"%' Group by func.classCodeGroup");
			}
		}else if(funcstr.length()==32){//在修改时使用
			templist=dao.find("from TitleFunc where funcId = '"+funcstr+"'");
			String str=((TitleFunc)templist.get(0)).getClassCodeGroup();
			olist=dao.find("select func,cla from TitleFunc func,TitleClass cla where cla.classCode='"+str.subSequence(0, 2)+"' and " +
					"func.classCodeGroup like '"+str.subSequence(0, 2)+"%' Group by func.classCodeGroup");
			}else{//在栏目管理时使用
				olist=dao.find("select func,cla from TitleFunc func,TitleClass cla where cla.classCode=SUBSTRING(func.classCodeGroup,1,2)  Group by func.classCodeGroup");
			}
		return olist;
	}
	
	
	/**
	 * 查找所有功能大类
	 * @param
	 * @return
	 */
	public List<TitleClass> searchTitle(){
		List<TitleClass> olist=dao.find("from TitleClass Order by classCode");
		return olist;
	}

	@Override
	public BaseDept findDeptByUserId(String userId) {
		// TODO Auto-generated method stub
		BaseDept dept = new BaseDept();
		String hql = "select dept from BaseUser user,BaseDept dept where user.deptId=dept.deptId and user.userId='"+userId+"'";
		
		List list = dao.find(hql);
		
		if(list.size() > 0 ){
			dept = (BaseDept)list.get(0);
		}
		
		return dept;
	}
}
